package com.bigwork.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bigwork.dto.order.OrderCreateRequest;
import com.bigwork.dto.order.OrderResponse;
import com.bigwork.dto.order.OrderStatusUpdateRequest;
import com.bigwork.entity.User;
import com.bigwork.exception.ResourceNotFoundException;
import com.bigwork.exception.UnauthorizedOperationException;
import com.bigwork.mapper.UserMapper;
import com.bigwork.service.OrderService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.web.bind.annotation.*;
import java.util.List;

@RestController
@RequestMapping("/api/orders")
@RequiredArgsConstructor
@Slf4j
public class OrderController {

    private final OrderService orderService;
    private final UserMapper userMapper;

    @PostMapping
    public ResponseEntity<OrderResponse> createOrder(@Valid @RequestBody OrderCreateRequest request, Authentication authentication) {
        User currentUser = getCurrentAuthenticatedUser(authentication);
        if (!currentUser.getId().equals(request.getUserId())) {
            throw new UnauthorizedOperationException("不能为其他用户创建订单");
        }
        log.info("API call to create order for user ID: {}", request.getUserId());
        OrderResponse createdOrder = orderService.createOrder(request);
        return new ResponseEntity<>(createdOrder, HttpStatus.CREATED);
    }

    @GetMapping("/{orderNumber}")
    public ResponseEntity<OrderResponse> getOrderByNumber(@PathVariable String orderNumber, Authentication authentication) {
        log.info("API call to get order by number: {}", orderNumber);
        OrderResponse order = orderService.getOrderDetailsByOrderNumber(orderNumber);
        User currentUser = getCurrentAuthenticatedUser(authentication);
        // Admin can view any order, user can only view their own
        if (!order.getUserId().equals(currentUser.getId()) && !authentication.getAuthorities().contains(new SimpleGrantedAuthority("ROLE_ADMIN"))) {
            throw new UnauthorizedOperationException("无权查看此订单");
        }
        return ResponseEntity.ok(order);
    }

    @GetMapping("/my-orders")
    public ResponseEntity<List<OrderResponse>> getMyOrders(Authentication authentication) {
        User currentUser = getCurrentAuthenticatedUser(authentication);
        log.info("API call to get all orders for current user ID: {}", currentUser.getId());
        List<OrderResponse> orders = orderService.getOrdersByUserId(currentUser.getId());
        return ResponseEntity.ok(orders);
    }

    @PutMapping("/{orderNumber}/status")
    @PreAuthorize("hasAuthority('ROLE_ADMIN')") // 只有管理员可以修改订单状态
    public ResponseEntity<OrderResponse> updateOrderStatus(
            @PathVariable String orderNumber,
            @Valid @RequestBody OrderStatusUpdateRequest request) {
        log.info("API call to update order {} status to {}", orderNumber, request.getStatus());
        OrderResponse updatedOrder = orderService.updateOrderStatus(orderNumber, request.getStatus());
        return ResponseEntity.ok(updatedOrder);
    }

    private User getCurrentAuthenticatedUser(Authentication authentication) {
        String username = authentication.getName();
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("username", username));
        if (user == null) {
            throw new ResourceNotFoundException("当前登录用户不存在");
        }
        return user;
    }
}